package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.AppointmentOrderService;

import com.itheima.health.util.SMSUtils;
import com.itheima.health.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预约控制层
 *
 * @author snowsee
 * @date 2023/4/27 10:41
 */
@RestController
@Slf4j
@RequestMapping("/mobile")
public class AppointmentOrderController {
    @Autowired
    private AppointmentOrderService appointmentOrderService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 提交预约
     * @param map
     * @return
     */
    @PostMapping("/order/submit")
    public Result submit(@RequestBody Map map){
        // 验证码校验
        // 拿到输入的手机号和验证码
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();
        if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(validateCode))
            throw new BusinessRuntimeException(MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        // 拿到redis中的验证码
        String codeInSession = (String)redisTemplate.opsForValue().get(telephone);
        if (StringUtils.isEmpty(codeInSession))
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        // 比对验证码
        String[] split = codeInSession.split("\\.");
        String type = split[0];
        String code = split[1];
        if (!"ORDER".equals(type))
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        if (!code.equals(validateCode))
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        // 验证会员 如果不是会员就注册 然后返回主键
        Member member = new Member();
        member.setPhoneNumber(telephone);
        member.setIdCard(map.get("idCard").toString());
        member.setName(map.get("name").toString());
        member.setSex(map.get("sex").toString());
        member = this.appointmentOrderService.saveByPhoneNumber(member);
        // 验证日期
        String orderDate = map.get("orderDate").toString();
        if (StringUtils.isEmpty(orderDate))
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);

        // 验证预约是否已满
        this.appointmentOrderService.getOrderSettingByOrderDate(orderDate);
        // 制作订单
        Order order = new Order();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse(orderDate);
            order.setOrderDate(new java.sql.Date(date.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        order.setMemberId(member.getId());
        Integer setmealId = Integer.valueOf(map.get("setmealId").toString());
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(setmealId);
        // 存入预约信息&设置表+1
        this.appointmentOrderService.saveOrderAndSetting(order);
        // 删除redis
        this.redisTemplate.delete(telephone);
        return new Result(true, MessageConst.ORDER_SUCCESS,order);
    }

    /**
     * 发送验证码
     * @param type
     * @param telephone
     * @return
     */
    /*@PostMapping("/validateCode/send")
    public Result validateCode(String type, String telephone, HttpSession httpSession){
        // 判断验证码类型
        if (!"ORDER".equals(type))
            return new Result(false, MessageConst.SEND_VALIDATECODE_FAIL);
        if (telephone == null)
            return new Result(false, MessageConst.SEND_VALIDATECODE_FAIL);
        // 生成四位验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("validateCode:{}", validateCode);
        // 发送验证码
        SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", telephone, validateCode);
        // 存入session
        httpSession.setAttribute(telephone, validateCode);
        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
    }*/
}
